package cn.bd13.swagger.controller;

import cn.bd13.swagger.entity.*;
import cn.bd13.swagger.service.AdminService;
import cn.bd13.swagger.utils.RedisUtil;
import cn.bd13.swagger.utils.ReturnUtils;
import cn.bd13.swagger.utils.TokenUtils;
import com.alibaba.fastjson.JSON;
import cz.mallat.uasparser.UserAgentInfo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * ClassName：AppController
 * Package:cn.bd13.swagger.controller
 * Description:
 *
 * @Date:2020/5/18 15:39
 * @Author:zhangqiang@kgc.cn
 */
@RestController
@Api("这是有app的admincontroller")
@RequestMapping("/admin")
public class AppController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisUtil redisUtil;

    @ApiOperation(value = "token方式登录",notes = "。。。")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "adminPhone",required = true,paramType = "path"),
            @ApiImplicitParam(name = "password",required = true,paramType = "path")
    })
    @ApiResponses({
            @ApiResponse(code = 403,message = "密码错误"),
            @ApiResponse(code = 406,message = "手机号错误"),
            @ApiResponse(code = 502,message = "数据库操作错误")
    })
    @RequestMapping(value = "/loginByPwd",method = RequestMethod.POST)
    public ReturnResult loginByPwd(@RequestBody LoginForm loginForm, HttpServletRequest request){
        //检查登录信息是否正确
        try {
            Admin admin = adminService.getAdminPhone(loginForm.getAdminPhone());

            if (admin!=null){
                if (loginForm.getPassword().equals(admin.getPassword())){
                    //检查正确
                    //解析这个请求的设备信息
                    String userAgent= request.getHeader("User-Agent");
                    UserAgentInfo userAgentInfo= TokenUtils.uaSparser.parse(userAgent);
                    String dType=userAgentInfo.getDeviceType();
                    //生成token
                    //String token= TokenUtils.createToken(user.getName());
                    String token=TokenUtils.createToken(admin.getAdminName(),dType);
                    //将token存入redis（先判断redis中有没有）
                    saveToken(token,admin);
                    //这是将用户信息放在data中，token信息放在msg中
                    return ReturnUtils.returnSuccessWithData(admin,token);
//                    Map<String,Object> dataMap=new HashMap<>();
//                    dataMap.put("user",user);
//                    dataMap.put("token",token);
//                    return ReturnUtils.returnSuccessWithData(dataMap);
                }else{
                    //密码错误
                    return ReturnUtils.returnFailed(403);
                }
            }else{
                //昵称错误
                return ReturnUtils.returnFailed(406);
            }
        } catch (Exception e) {
            //查询中出现异常
            e.printStackTrace();
            return ReturnUtils.returnFailed(502);
        }
    }


    @RequestMapping("/getAllAdminInfo")
    public ReturnResult getAllUserInfo(HttpServletRequest request){

        String token = request.getHeader("token");
        if (token==null||token.equals("")){
            return ReturnUtils.returnFailed(403,"没有登录,请先登录");
        }else{
            String userJson=redisUtil.get(token);
            if (userJson==null||userJson.equals("")){
                return ReturnUtils.returnFailed(403,"没有权限,请登录");
            }else{
                try {
                    Admin admin = (Admin) JSON.parseObject(userJson,Admin.class);
                    List<Admin> admins=adminService.getAllAdmin();
                    return ReturnUtils.returnSuccessWithData(admins,"你是："+admin.getAdminName());
                } catch (Exception e) {
                    e.printStackTrace();
                    return ReturnUtils.returnFailed(500);
                }
            }

        }


    }

    @ApiOperation(value = "菜单列表",notes = "。。。")
    @ApiResponses({
            @ApiResponse(code = 501,message = "redis缓存错误"),
            @ApiResponse(code = 502,message = "数据库操作错误")
    })
    @GetMapping("/getMenus")
    public ReturnResult getMenus(HttpServletRequest request){
        //通过token获取管理员信息
        String token=request.getHeader("token");
        String adminJson="";
        try {
            adminJson=redisUtil.get(token);
        }catch (Exception e){
            e.printStackTrace();
            return  ReturnUtils.returnFailed(501,"redis error");
        }
        Admin admin;
        //转换为admin对象
        if(adminJson!=""){
            admin=JSON.parseObject(adminJson,Admin.class);
        }else {
            return  ReturnUtils.returnFailed(501,"redis error");
        }

        //String adminJson=redisUtil.get(token);
        //Admin admin=JSON.parseObject(adminJson,Admin.class);
        int adminType=admin.getAdminType();
        //通过类型获取菜单数据
        try {
            List<MenuVo> menus=adminService.getMenuByAtype(adminType);
            return ReturnUtils.returnSuccessWithData(menus);
        }catch (Exception e){
            e.printStackTrace();
            return  ReturnUtils.returnFailed(502,"mysql error");
        }



    }

    private void saveToken(String token,Admin admin)throws Exception{

        String tokenKey="user-"+admin.getAid();
        String tokenValue=null;
        if ((tokenValue=redisUtil.get(tokenKey))!=null){
            //用户已经登录过，而且没有过期
            redisUtil.delete(tokenKey);
        }
        //缓存用户
        redisUtil.set(tokenKey,token,100);
        //缓存用户信息
        redisUtil.set(token, JSON.toJSONString(admin),1800);
    }
}
